package rapier.sso.server.handler.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import rapier.sso.core.config.redis.RedisClient;
import rapier.sso.server.constant.RapierServerConstant;
import rapier.sso.server.handler.IAppAuthHandler;
import rapier.sso.server.model.AppCredential;

@Component
public class CaptchaAppAuthHandler implements IAppAuthHandler {

	@Autowired
	private RedisClient redisClient;

	@Override
	public boolean support(AppCredential credential) {
		if(credential.getLoginModel() == null) {
			return false;
		}
		return StringUtils.isNotBlank(credential.getLoginModel().getCaptchaKey());
	}

	@Override
	public boolean auth(AppCredential credential) {
		String captchaVal = credential.getLoginModel().getCaptchaVal();
		String captchaKey = credential.getLoginModel().getCaptchaKey();
		Object redisCaptcha = redisClient.get(RapierServerConstant.REDIS_SSO_USER_CAPTCHA_KEY + captchaKey);
		// 判断验证码
		if (redisCaptcha == null || !redisCaptcha.toString().equals(captchaVal.trim())) {
			credential.setError("验证码错误!");
			return false;
		}
		return true;
	}

	@Override
	public void release(AppCredential credential) {
		String captchaKey = credential.getLoginModel().getCaptchaKey();
		redisClient.remove(RapierServerConstant.REDIS_SSO_USER_CAPTCHA_KEY + captchaKey);
	}
}
